package cn.zyy.hotel.service.impl;

import cn.zyy.hotel.dao.OrdersMapper;
import cn.zyy.hotel.dao.RoomMapper;
import cn.zyy.hotel.dao.RoomTypeMapper;
import cn.zyy.hotel.entity.Orders;
import cn.zyy.hotel.entity.Room;
import cn.zyy.hotel.entity.RoomType;
import cn.zyy.hotel.service.OrdersService;
import cn.zyy.hotel.utils.UUIDUtils;
import cn.zyy.hotel.vo.OrdersVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrdersServiceImpl implements OrdersService {

    private static final Logger logger = LoggerFactory.getLogger(OrdersServiceImpl.class);
    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private RoomMapper roomMapper;

    @Resource
    private RoomTypeMapper roomTypeMapper;

    //添加订单
    @Transactional(rollbackFor = RuntimeException.class)
    public int addOrders(Orders orders) {
        orders.setStatus(1);//1-待确认
        orders.setReserveDate(new Date());//预定时间为当前系统时间
        int line = ordersMapper.addOrders(orders);
        //判断订单是否添加成功，添加成功操作房间及房型
        if (line > 0){
            //修改房间状态为已预订
            //查询房间信息
            Room room = roomMapper.selectById(orders.getRoomId());
            room.setStatus(1);
            //调用修改房间信息的方法
            roomMapper.updateRoom(room);
            //修改房型(可用房间数-1，已预订数量+1)
            RoomType roomType = roomTypeMapper.selectById(orders.getRoomTypeId());
            //修改可用房间数量
            roomType.setAvilableNum(roomType.getAvilableNum()-1);
            //修改已预订数量
            roomType.setReservedNum(roomType.getReservedNum()+1);
            //调用修改房型的方法
            roomTypeMapper.updateRoomType(roomType);
        }
        return line;
    }

    //查询订单列表
    public List<Orders> selectOrdersList(OrdersVO ordersVO) {
        return ordersMapper.selectOrdersList(ordersVO);
    }

    //修改订单
    public int updateOrders(Orders orders) {
        return ordersMapper.updateOrders(orders);
    }

    //根据用户id查询订单
    @Override
    public List<Orders> selectOrdersListByUserId(Integer id) {
        return ordersMapper.selectOrdersListByUserId(id);
    }


}
